package org.novudu.presentation.actions;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.dialogs.ListSelectionDialog;
import org.eclipse.update.core.IFeature;
import org.eclipse.update.core.IFeatureReference;
import org.eclipse.update.core.ISite;
import org.eclipse.update.core.ISiteFeatureReference;
import org.eclipse.update.core.SiteManager;
import org.eclipse.update.core.VersionedIdentifier;
import org.novudu.Feature;
import org.novudu.NovuduFactory;
import org.novudu.Product;
import org.novudu.presentation.NovuduEditor;
import org.novudu.presentation.NovuduEditorPlugin;

public class FetchFeaturesAction implements IObjectActionDelegate {
	
	protected Product product;
	protected IWorkbenchPart targetPart;
	
	@Override
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		this.targetPart = targetPart;
	}
	
	@Override
	public void run(IAction action) {
		
		final List<IFeature> features = new ArrayList<IFeature>();
		
		Job job = new Job("Fetching features") {

			@Override
			protected IStatus run(IProgressMonitor monitor) {
				try {
					ISite site = SiteManager.getSite(new URL(product.getUpdatesite()));
					for (ISiteFeatureReference reference : site.getFeatureReferences()) {
						features.add(reference.getFeature());
					}
				}
				catch (Exception ex) {
					ex.printStackTrace();
					return new Status(Status.ERROR, "org.novudu.editor", ex.getMessage());
				}
				return Status.OK_STATUS;
			}
			
		};
		
		job.setUser(true);
		job.schedule();
		
		while (job.getResult() == null) {}
		
		if (!(job.getResult() == Status.OK_STATUS)) return;
		
		FeatureListSelectionDialog dialog = new FeatureListSelectionDialog(targetPart.getSite().getShell(), features, "Available features");
		dialog.setBlockOnOpen(true);
		
		if (dialog.open() == Window.OK) {
			for (Object o : dialog.getResult()) {
				Feature feature = NovuduFactory.eINSTANCE.createFeature();
				feature.setEnabled(true);
				feature.setVersion("latest");
				feature.setId(((IFeature)o).getVersionedIdentifier().getIdentifier());
				product.getFeatures().add(feature);
				System.err.println(feature);
			}
		}
		
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		product = (Product) ((IStructuredSelection)selection).getFirstElement();
	}

}
